package be.kuleuven.cs.mop.domain.model.impl;


import java.util.Collections;
import java.util.Comparator;
import java.util.List;



/**
 * Duration-based {@link FocusWorkAlgorithm}
 */
public class FocusWorkAlgorithmDuration extends FocusWorkAlgorithm {
	
	/**
	 * The duration boundaries
	 */
	private final int max, min;
	
	/**
	 * Represents a duration-based template method implementation for the "Focus Work" use case
	 */
	public FocusWorkAlgorithmDuration(final UserImpl user,
			final int min, final int max) {
		super(user);
		if ((min < 0) || (max < 0) || (min == max) || (min > max))
			throw new IllegalArgumentException("Illegal bounds");
		this.max = max;
		this.min = min;
	}
	
	
	/**
	 * Compares two tasks based on their duration
	 */
	protected Comparator<TaskImpl> getComparator() {
		return new Comparator<TaskImpl>() {
			@Override
			public int compare(final TaskImpl a, final TaskImpl b) {
				return new Long(a.getSchedule().getDuration()).compareTo(
						b.getSchedule().getDuration());
			}
		};
	}

	/**
	 * Sorts the list of tasks based on the comparator above
	 */
	@Override
	protected void sort(final List<TaskImpl> tasks) {
		Collections.sort(tasks, getComparator());
	}

	/**
	 * Filters all tasks out whos deadline is not within the deadline bounds
	 */
	@Override
	protected void filter(List<TaskImpl> tasks) {
		for (final TaskImpl task : tasks.toArray(new TaskImpl[tasks.size()])) {
			final long duration = task.getSchedule().getDuration();
			if ((duration <= min) || (duration >= max))
				tasks.remove(task);
		}
	}
	
}